package com.rg.inf.receiver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rd.sys.common.base.CommonConstants;
import com.rd.sys.common.utils.JacksonMapper;
import com.rd.sys.dto.commmon.base.EyeException;
import com.rd.sys.dto.commmon.base.EyeResult;
import com.rg.inf.action.DispatchAction;

public class SynServlet extends javax.servlet.http.HttpServlet {
    private static final long serialVersionUID = 6647651195373870689L;
    protected static final Logger logger = LoggerFactory.getLogger(SynServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        try {
            /** 1. 获得Http Body中的消息串 */
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(),
                    CommonConstants.SysParamConstants.SYS_CHARSET));

            String userCode = reader.readLine(); // 根据协议,第一行为用户编码
            StringBuffer msgBuffer = new StringBuffer();// 第二行后都是加密后的消息原文
            String message = null;
            while ((message = reader.readLine()) != null) {
                msgBuffer.append(message);
            }
            message = msgBuffer.toString();

            reader.close();// 关闭缓冲流

            if (StringUtils.isEmpty(userCode) || StringUtils.isEmpty(message)) {
                throw new Exception("receive message is empty."); // 抛出异常
            } else {
                logger.info("the request message is: userCode = " + userCode + ", message = " + message);
            }

            /** 2. 交由统一分发Action处理 */
            String respMessage = new DispatchAction().execute(userCode, message);

            /** 3. 响应给客户端 */
            response2Client(response, respMessage);
        } catch (EyeException ex) {
            response2ClientError(response, new EyeResult(ex.getResult()));
        } catch (Exception ex) {
            logger.error("", ex);
            response2ClientError(response, new EyeResult(EyeResult.ResultDefine.COMMON_OTHER_ERROR_CLIENT));
        }
    }

    /**
     * 响应给客户端
     * 
     * @param response
     * @param interBossResp
     * @throws IOException
     */
    private void response2Client(HttpServletResponse response, String respMessage) throws IOException {
        logger.info("the response message is: " + respMessage);
        response.setCharacterEncoding(CommonConstants.SysParamConstants.SYS_CHARSET);
        response.setHeader("Content-Type", "application/x-www-form-urlencoded");

        PrintWriter writer = response.getWriter();
        writer.print(respMessage);
        writer.flush();
        writer.close();
    }

    /**
     * 响应给客户端(400错误码)
     * 
     * @param response
     * @param result
     * @throws IOException
     */
    private void response2ClientError(HttpServletResponse response, EyeResult result) throws IOException {
        String respMessage = JacksonMapper.bean2Json(result);
        logger.info("the response message is: " + respMessage);
        response.setCharacterEncoding(CommonConstants.SysParamConstants.SYS_CHARSET);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, respMessage);
    }
}
